package com.pz.chat.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.pz.chat.constant.MessageTypeEnum;
import com.pz.chat.entity.ChatMessageEntity;
import com.pz.chat.entity.MemberEntity;
import com.pz.chat.entity.MemberFocusEntity;
import com.pz.chat.dao.MemberFocusDao;
import com.pz.chat.entity.resultmap.MemberFocusResultMap;
import com.pz.chat.service.ChatMessageService;
import com.pz.chat.service.MemberFocusService;
import com.pz.chat.service.MemberService;
import com.pz.chat.vo.*;
import com.pz.gulimall.common.exception.BizCodeEnum;
import com.pz.gulimall.common.exception.RRException;
import com.pz.gulimall.common.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("memberFocusService")
public class MemberFocusServiceImpl extends ServiceImpl<MemberFocusDao, MemberFocusEntity> implements MemberFocusService {

    @Autowired
    private MemberService memberService;
    @Autowired
    private ChatMessageService chatMessageService;

    @Override
    public void addFocus(AddFocusApplyReqVo vo) {
        MemberFocusEntity memberFocus = new MemberFocusEntity(vo.getFromId(), vo.getToId(), 0, new Date());
        this.save(memberFocus);
    }

    /**
     * 处理好友申请请求
     */
    @Transactional
    @Override
    public void handle(HandleFocusApplyReqVo vo) {
        if(vo.getAck() == 1) {
            this.remove(new QueryWrapper<MemberFocusEntity>()
                    .eq("from_member_id", vo.getToId()).eq("to_member_id", vo.getFromId())
            );
            this.remove(new QueryWrapper<MemberFocusEntity>()
                    .eq("from_member_id", vo.getFromId()).eq("to_member_id", vo.getToId())
            );
            MemberFocusEntity memberFocus1 = new MemberFocusEntity(vo.getFromId(), vo.getToId(), 1, new Date());
            MemberFocusEntity memberFocus2 = new MemberFocusEntity(vo.getToId(), vo.getFromId(), 1, new Date());
            this.save(memberFocus1);
            this.save(memberFocus2);
        }
        if(vo.getAck() == -1) {
            this.update(new UpdateWrapper<MemberFocusEntity>()
                    .set("ack", vo.getAck())
                    .set("focus_time", new Date())
                    .eq("from_member_id", vo.getToId() ).eq("to_member_id", vo.getFromId())
            );
        }
    }

    /**
     * 获取 {userId} 的好友申请列表（收到的申请）
     */
    @Override
    public List<FocusApplyItemResVo> listFocusApply(Long userId) {
        // 收到的申请
        List<MemberFocusEntity> focusEntities = this.list(new QueryWrapper<MemberFocusEntity>()
                .eq("to_member_id", userId)
                .orderByDesc("focus_time")
        );
        Set<Long> idSet = new HashSet<>();
        // 收到的申请列表
        List<FocusApplyItemResVo> ans = new ArrayList<>();
        focusEntities.forEach(item -> {
            if(!idSet.contains((item.getFromMemberId()))) {
                FocusApplyItemResVo temp = new FocusApplyItemResVo();
                MemberEntity member = memberService.getById(item.getFromMemberId());
                BeanUtils.copyProperties(member, temp);
                temp.setApplyTime(item.getFocusTime());
                temp.setAck(item.getAck());
                ChatMessageEntity one = chatMessageService.getOne(new QueryWrapper<ChatMessageEntity>()
                        .eq("type", MessageTypeEnum.FOCUS_APPLY.getType())
                        .and(
                                q1 -> q1.eq("from_id", item.getFromMemberId()).eq("to_id", item.getToMemberId()))
                        .orderByDesc("send_time")
                        .last("LIMIT 1")
                );
                if(one != null){
                    temp.setGreetingMsg(one.getMsgContent());
                }
                ans.add(temp);
                idSet.add(item.getFromMemberId());
            }
        });
        return ans;
    }

    @Override
    public R queryMemberFocus(MemberFocusSearchReqVo vo) {
        if(vo.getType().equals("my-focus")) {
            // 搜索自己的关注列表
            List<MemberFocusResultMap> memberFocus;
            if(StringUtils.isEmpty(vo.getKey())) {
                memberFocus = this.baseMapper.queryMyFocus(vo.getUserId(), null);
            } else {
                memberFocus = this.baseMapper.queryMyFocus(vo.getUserId(), vo.getKey());
            }
            return R.ok().put("data", memberFocus);
        }
        if(vo.getType().equals("add-focus") && !StringUtils.isEmpty(vo.getKey())) {
            // 全局搜索用户
            //member.nickname LIKE '%test%' OR mem.username LIKE '%test%' OR mem.mobile = '' OR mem.email = ''
            List<MemberEntity> list = memberService.list(new QueryWrapper<MemberEntity>()
                    .like("nickname", vo.getKey())
                    .or().like("username", vo.getKey())
                    .or().eq("mobile", vo.getKey())
                    .or().eq("email", vo.getKey())
            );
            List<MemberSearchResVo> ans = new ArrayList<>();
            for (MemberEntity member : list) {
                // 把自己排除掉
                if (member.getId().longValue() != vo.getUserId()){
                    MemberSearchResVo temp = new MemberSearchResVo();
                    temp.setUserId(vo.getUserId());
                    BeanUtils.copyProperties(member, temp);

                    MemberFocusEntity one = this.getOne(new QueryWrapper<MemberFocusEntity>()
                            .eq("from_member_id", temp.getUserId()).eq("to_member_id", member.getId())
                            .orderByDesc("focus_time")
                            .last("LIMIT 1")
                    );
                    if(one == null){
                        temp.setFocusStatus(2);
                    } else {
                        temp.setFocusStatus(one.getAck());
                    }
                    ans.add(temp);
                }
            }
            return R.ok().put("data", ans);
        } else if (StringUtils.isEmpty(vo.getKey())) {
            return R.ok();
        }
        throw new RRException(BizCodeEnum.MEMBER_SEARCH_TYPE_ILLEGAL);
    }

    /**
     * 获取{userId} 发起的好友申请
     */
    @Override
    public List<FocusApplyItemResVo> listMyApply(Long userId) {
        // 发起的申请
        List<MemberFocusEntity> focusEntities = this.list(new QueryWrapper<MemberFocusEntity>()
                .eq("from_member_id", userId)
                .orderByDesc("focus_time")
        );
        // 发起的申请列表
        List<FocusApplyItemResVo> ans = new ArrayList<>();
        Set<Long> idSet = new HashSet<>();
        focusEntities.forEach(item -> {
            if(!idSet.contains(item.getToMemberId())) {
                FocusApplyItemResVo temp = new FocusApplyItemResVo();
                MemberEntity member = memberService.getById(item.getToMemberId());
                BeanUtils.copyProperties(member, temp);
                temp.setApplyTime(item.getFocusTime());
                temp.setAck(item.getAck());
                ChatMessageEntity one = chatMessageService.getOne(new QueryWrapper<ChatMessageEntity>()
                        .eq("type", MessageTypeEnum.FOCUS_APPLY.getType())
                        .and(
                                q1 -> q1.eq("from_id", userId).eq("to_id", item.getToMemberId()))
                        .orderByDesc("send_time")
                        .last("LIMIT 1")
                );
                if(one != null){
                    temp.setGreetingMsg(one.getMsgContent());
                }
                ans.add(temp);
                idSet.add(item.getToMemberId());
            }
        });
        return ans;
    }
}
